<template>
  <!------------------子组件----------------->
  <el-form ref="form" :rules="rules" :model="form" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <!-- 从后端传来的数据，list = res.data(是一个数组) -->
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getEmployeeSimple, addDepartment, getDepartmentById, updataDepartment } from '@/api/departments'

export default {
  // --------------------------------------------父传子数据
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  // --------------------------------------------数据
  data() {
    const validCode = (rule, value, callback) => {
      console.log(value) // 要校验的code abc
      // originList = [{code:'01' ,id:xxx},{code:'02' ,id:xxx}]
      // ['01', '02']
      const codeList = this.originList.map(item => item.code)
      console.log(codeList) // originList中的16个code是不能取的
      // 如果是编辑 要排除当前正在编辑的部门编号
      if (this.isEdit) {
        // this.pid是当前正在被编辑的部门编号
        // 1.把当前的部门排除在外
        // 2.得到编号
        this.originList.filter(item => item.id !== this.pid).map(item => item.code)
        if(this.isEdit){
          // 如果是编辑状态，则不能取得名字是：当前部门的兄弟部门 - 它自己的名字
        const item =  this.originList.find(item=>item.id ===this.pid)
        const pid = item.pid
        nameList = this.originList.filter(item => item.pid ===pid&&item.id!==this.pid).map(item=>item.name)
        console.log(nameList)
        }
      }

      // if(value 在 this.originList) {
      if (codeList.includes(value)) {
        callback(new Error(value + '被占用了'))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      // value是要校验的名字
      // 添加时候: 不能现有的同级部门重名
      // 当前点击的部门id 是 this.pid
      // 找出子部门
      const nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      console.log(nameList)
      // 如果 value 在nameList中存在 说明名字重复了
      if (nameList.includes(value)) {
        callback(new Error(value + '被占用'))
      } else {
        callback()
      }
    }
    return {
      // ---------------------------------------校验规则
      rules: {
        name: [
          { required: true, message: '部门名字不能为空', trigger: 'blur'
          },
          { min: 2, max: 50, message: '部门名字不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      // ---------------------------------------基础信息数据
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        clod: ''
      },
      // ---------------------------------------空数组
      list: []
    }
  },
  // --------------------------------------------页面渲染钩子
  created() {
    this.losdSimpleEmployee()
    // 如果是编辑就获取员工id
    if (this.isEdit) {
      this.loadDepartmentById()
    }
  },
  methods: {
    // ------------------------------------------页面渲染请求
    async losdSimpleEmployee() {
      const rs = await getEmployeeSimple()
      console.log(rs)
      this.list = rs.data
    },
    // ------------------------------------------获取id请求
    async loadDepartmentById() {
      const res = await getDepartmentById(this.pid)
      console.log('现在是编辑', res)
      // 数据回填
      this.form = res.data
    },
    // ------------------------------------------调用添加请求
    async doAdd() {
      // 调用接口
      try {
        await addDepartment({ ...this.form, pid: this.pid })
        // 通知父组件操作成功
        this.$emit('success')
      } catch (err) {
        // 没有填写代码，就走这行代码
        console.log(err)
      }
    },
    // ------------------------------------------调用编辑请求
    async doEdit() {
      try {
        await updataDepartment(this.form)
        this.$emit('success')
      } catch (err) {
        console.log(err)
      }
    },
    // ------------------------------------------兜底校验并确认添加成功
    hSubmit() {
      // 表单兜底校验
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // ------------------------------------------点击取消并关闭弹层
    hCancel() {
      // 关闭弹层
      // 抛出事件
      this.$emit('close')
    }
  }
}
</script>
